package com.liuwei.msmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liuwei.msmall.common.utils.PageUtils;
import com.liuwei.msmall.common.utils.Query;
import com.liuwei.msmall.product.dao.BrandDao;
import com.liuwei.msmall.product.entity.BrandEntity;
import com.liuwei.msmall.product.entity.CategoryBrandRelationEntity;
import com.liuwei.msmall.product.service.BrandService;
import com.liuwei.msmall.product.service.CategoryBrandRelationService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Resource
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                new QueryWrapper<BrandEntity>()
        );
        IPage<BrandEntity> brandEntityIPage = this.baseMapper.selectPage(new Page<>(1, 10), new QueryWrapper<BrandEntity>());
        return new PageUtils(page);
    }

    /**
     * 更新自己的同时,更新pms_category_brand_relation关联表
     * @param brand
     */
    @Transactional
    @Override
    public void updateCascade(BrandEntity brand) {
        this.baseMapper.updateById(brand);
        CategoryBrandRelationEntity categoryBrandRelationEntity = new CategoryBrandRelationEntity();
        categoryBrandRelationEntity.setBrandName(brand.getName());
        categoryBrandRelationEntity.setBrandId(brand.getBrandId());
        categoryBrandRelationService.update(categoryBrandRelationEntity,new UpdateWrapper<CategoryBrandRelationEntity>().eq("brand_id",brand.getBrandId()));
    }

    @Transactional
    @Override
    public void removeByIdsCascade(List<Long> asList) {
        //TODO 判断关联的商品

        //删除品牌关联表
        categoryBrandRelationService.remove(new QueryWrapper<CategoryBrandRelationEntity>().in("brand_id",asList));

        //删除自己
        this.removeByIds(asList);

    }

}